package com.yongchun.wxCommons.business;

import com.yongchun.commons.YXDate;
import com.yongchun.wxCommons.wxConfig.SkWxPayConfig;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author xy
 * @Date 2020/5/28 09:59
 * @description
 */

@Component
public class SkWxPayService {


    @Autowired
    private WxPayService wxPayService;

    /**
     * 创建wx统一订单
     *
     * @param payData
     * @return
     * @throws WxPayException
     */
    public WxPayMpOrderResult createOrder(WxPayData payData) throws WxPayException {

        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setOpenid(payData.getWxOpenId());
        orderRequest.setSpbillCreateIp(payData.getIp());
        orderRequest.setBody(payData.getBody());

        if (wxPayService.getConfig() instanceof SkWxPayConfig && ((SkWxPayConfig) wxPayService.getConfig()).isDebug()) {
            orderRequest.setTotalFee(1);
        } else {
            orderRequest.setTotalFee(payData.getTotalFee());
        }


        orderRequest.setOutTradeNo(payData.getOutTradeNo());
        orderRequest.setNotifyUrl(payData.getNotifyUrl());

        orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
        orderRequest.setSignType(WxPayConstants.SignType.MD5);
        Date now = new Date();
        Date afterDate = YXDate.addSeconds(now, 300);
        orderRequest.setTimeStart(YXDate.getFormatDate2String(now, "yyyyMMddHHmmss"));
        orderRequest.setTimeExpire(YXDate.getFormatDate2String(afterDate, "yyyyMMddHHmmss"));

        return wxPayService.createOrder(orderRequest);
    }


}
